package remotecontrol;

import java.awt.AWTException;
import java.awt.Desktop;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JOptionPane;

import javazoom.jl.decoder.JavaLayerException;

import com.gtranslate.Audio;
import com.gtranslate.Language;

import datalayer.DBobject;
import Model.Nummer;
import Model.PlayerModel;
import View.PlayerView;
import onebeartoe.AppModes;
import onebeartoe.Standard;
import onebeartoe.juke.RandomJuke;
import onebeartoe.juke.services.CurrentSongService;
import onebeartoe.juke.services.SongsPlayedService;
import onebeartoe.media.BasicMultimediaController;
import onebeartoe.media.MultimediaController;
import onebeartoe.net.ServerConnection;
import onebeartoe.xhtml.CodeGenerator;
import remotecontrol.RandomJukeMain;

// Referenced classes of package onebeartoe.juke:
//            RandomJuke

public class Connect extends ServerConnection
{

	private static final int ArrayIndexOutOfBoundsException = 0;
	String hostName = InetAddress.getLocalHost().getHostName();
	
    public Connect() throws UnknownHostException, UnsupportedEncodingException
    {
    	InetAddress IP;
		IP = InetAddress.getLocalHost();
		String IPnieuw = IP.toString();
		Send.send(IPnieuw, hostName);
    }

    public void run()
    {
        try
        {
        	
            System.out.println((new StringBuilder(hostName+"/"+System.getProperty("user.name")+" is connected...").toString()));
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), "8859_1"));
            OutputStream outs = client.getOutputStream();
            PrintWriter out = new PrintWriter(new OutputStreamWriter(outs, "UTF-8"), true);
            String request = in.readLine();
     //       System.out.println((new StringBuilder("Request: ")).append(request).toString());
            Pattern pattern = Pattern.compile("GET /?(\\S*).*");
            Matcher get = pattern.matcher(request);
            
            String textfield = (new StringBuilder("")).append(request).toString();
            
            if (textfield.startsWith("GET /?textfield")) {
            	String str1 = textfield.replace("GET /?textfield=", "");
            	String str2 = str1.replace("HTTP/1.1", "");
            	String str3 = str2.replace("+", " ");
            	if (str3.startsWith("speak")) {
					Audio audio = Audio.getInstance();
					String speak = str3.replace("speak", "");
					System.err.println(speak);
					InputStream sound = audio.getAudio(speak, Language.DUTCH);
					audio.play(sound);
				}else{
            		
            		System.err.println(str3);
            		String input = JOptionPane.showInputDialog(str3);
	            	out.println("<script> alert('"+input+"');</script>");
                	}
                	
				}
 
            	
			
				
			
            if(get.matches())
            {
                request = get.group(1);
                if(request.endsWith("/") || request.equals(""))
                {
                    request = (new StringBuilder(String.valueOf(request))).append("index.html").toString();
                } else
                {
                    String parameters[] = request.split("&");
                    String as[];
                    int k = (as = parameters).length;
                    for(int j = 0; j < k; j++)
                    {
                        String param = as[j];
                        String nameValues[] = param.split("=");
                        if(nameValues.length == 2 && nameValues[0].equals("action"))
                        {
                //            String currentSongTitle = RandomJuke.currentSongTitle;
                            if(nameValues[1].equals("next"))
                               app.playNextSong();
                          
                          else
                            if(nameValues[1].equals("play"))
                                try
                                {
                                    app.play();
                                }
                                catch(Exception e)
                                {
                                    e.printStackTrace();
                                }
                            else
                            	if(nameValues[1].endsWith("previous")){
                            		app.playPreviousSong();
                            	}
                            	else if (nameValues[1].equals("volumedown")) {
									app.volumedown();
								}else if (nameValues[1].equals("volumemax")) {
									app.volumemax();
								}
//                            if(nameValues[1].equals(VOLUME_UP) && !(appMode == AppModes.REGULAR))
//                            {
//                                System.out.println((new StringBuilder("volume up requested, current level: ")).append(systemMediaControler.currentVolume()).toString());
//                                int volume = systemMediaControler.currentVolume() + 5;
//                                volume = volume <= 100 ? volume : 100;
//                                System.out.println((new StringBuilder("proposed new volume level: ")).append(volume).toString());
//                                systemMediaControler.setVolume(volume);
//                                System.out.println((new StringBuilder("after processing the UP request, current volume level is ")).append(systemMediaControler.currentVolume()).toString());
//                            } else
//                            if(nameValues[1].equals(VOLUME_DOWN) && !(appMode == AppModes.REGULAR))
//                            {
//                                System.out.println((new StringBuilder("volume DOWN requested, current level: ")).append(systemMediaControler.currentVolume()).toString());
//                                int volume = systemMediaControler.currentVolume() - 5;
//                                volume = volume >= 0 ? volume : 0;
//                                System.out.println((new StringBuilder("proposed new volume level: ")).append(volume).toString());
//                                systemMediaControler.setVolume(volume);
//                                System.out.println((new StringBuilder("after processing the DOWN request, current volume level is ")).append(systemMediaControler.currentVolume()).toString());
//                            }
                        }
                    }

                }
                

              	
    //            String heaersMessage = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n";
   //             heaersMessage = (new StringBuilder(String.valueOf(heaersMessage))).append("\r\n").toString();
   //             out.print(heaersMessage);
                String title = "Solid Kangaroo - Remote Access";
                out.println(Standard.htmlTop(title));
     //         out.println("<SCRIPT Language='JavaScript'> function showAndClearField(frm){ alert('frm.textfield.value')");
                out.println("</b></b>");
                out.println("<center>");
                out.println("<h1>Solid Kangaroo Remote v2.0</h1>");
                out.println("Beheer de Solid Kangaroo muziekspeler op afstand met <b>Solid Kangaroo Remote v2.0</b>");
                out.println("</center>");
                out.println("<hr>");
                out.println("<h2>Wat wil je doen?</h2>");
                out.println("<center>");
                String play = CodeGenerator.getLinkTag("action=play&more=less", "Play/Pause");
                out.println(play);
                out.println(" | ");
                String previous = CodeGenerator.getLinkTag("action=previous&more=less", "Previous");
                out.println(previous);
                out.println(" | ");
                String nextLink = CodeGenerator.getLinkTag("action=next&more=less", "Next");
                out.println(nextLink);
                out.println("<br>");
                out.println("<FORM NAME='formulier' ACTION=''>");
                out.println("<br><b>Stuur een berichtje naar "+System.getProperty("user.name")+" of gebruik de 'speak' functie</b><br> <input type='textfield' size='100' name='textfield'>");
                out.println("</FORM>");
                out.println("</center>");
                out.println("</br>");
                out.println("<hr>");
                if(!(appMode == AppModes.REGULAR))
                {
                    out.println("<center><h2>Volume</h2>");
                    String volumeDownLink =  CodeGenerator.getLinkTag("action=volumedown&more=less", "VOLUME DOWN");
                    out.println(volumeDownLink);
                    out.println("&nbsp;&nbsp;&nbsp;");
                    out.println("&nbsp;&nbsp;&nbsp;");
                    String volumeUpLink =  CodeGenerator.getLinkTag("action=volumemax&more=less", "VOLUME MAX");
                    out.println(volumeUpLink);
                    out.println("<hr/></center>");
                }
                
//                out.println("<br /><h3>Waar luistert"+System.getProperty("user.name")+" naar?</h3>");
//                out.println("<br />");
//                out.println("<div style=\"overflow: auto; height: 300px; background-color: gray;\">");
//                out.println("<ul>");
//                DBobject db = new DBobject();
//                ArrayList<Nummer> songs = new ArrayList<Nummer>();
//    			songs = db.loadDB();
//    			
//				
//				
//                String selectedSong = songs.get(PlayerView.lstSongs.getSelectedIndex()).getLocatie();
//                out.println("<h1>"+selectedSong+"</h1>");
			
                out.println("</ul>");
                out.println("</div>");
            //    out.println("<hr>");
                out.println("</br>");
            //    out.println("<hr>");
   //           songsPlayed = RandomJuke.songsPlayedService.getSongsPlayed();
   //             out.println(Standard.htmlBottom());
                out.flush();
            } else
            {
                out.println((new StringBuilder("Request Recieved Busta: ")).append(request).toString());
                out.print("<br /><br />Bobster accepts requests like \"GET filename.html\"<br />");
                out.print("<br /><br />or something like \"filename.zip\"<br />");
                out.flush();
            }
            out.close();
            client.close();
 //           System.out.println((new StringBuilder("closing Socket for: ")).append(request).toString());
        }
        catch(IOException e)
        {
            System.out.println((new StringBuilder("I/O error ")).append(e).toString());
        }
        catch(SecurityException se)
        {
            System.out.println((new StringBuilder("Security error: ")).append(se).toString());
        }
        catch(ArrayIndexOutOfBoundsException aoutb)
        {
        	System.err.println("Index Out Of Bounds Exception");
        } catch (JavaLayerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    public void setNextSongButton(JButton nextSongButton)
    {
        this.nextSongButton = nextSongButton;
    }

    public void setCurrentSongService(CurrentSongService currentSongService)
    {
        this.currentSongService = currentSongService;
    }

    public void setApp(RandomJukeMain randomJuke)
    {
        this.app = randomJuke;
    }

    public AppModes appMode;
    JButton nextSongButton;
    int POST_SIZE;
    private CurrentSongService currentSongService;
 //   private Player player;
    private RandomJukeMain app;
}
